﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;
using System.Windows.Media;

namespace Fayshine.VA.Views.DayStatistics
{
    public partial class DayChannelStatistics : Page
    {

        private SearchStatisticsViewModel m_ViewModel;

        public DayChannelStatistics()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DayChannelStatistics_Loaded);
        }

        #region Event Methods

        private void DayChannelStatistics_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                spContent.Children.Clear();
                Grid tableGrid = GetTableGrid();


                DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                              startDatePicker.SelectedDate.Value.Month,
                                              startDatePicker.SelectedDate.Value.Day,
                                              0, 0, 0);
                DateTime nextDate = startTime.AddDays(1);
                DateTime endTime = new DateTime(nextDate.Year,
                                                nextDate.Month,
                                                nextDate.Day,
                                                0, 0, 0);

                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                List<int> monitorAreaIDs = new List<int>();
                selectAreaExt.each(s => { monitorAreaIDs.Add(s.ID); });
                bool isSingleArea = monitorAreaIDs.Count == 1 ? true : false;
                if (isSingleArea)
                {
                    var topAreaGate = m_ViewModel.MonitorAreaGateExts.Where(m => m.TypeID == 1).FirstOrDefault();
                    if (topAreaGate != null)
                    {
                        List<int> ids = new List<int>();
                        if (topAreaGate.IsSelected)
                        {
                            ids = m_ViewModel.GetGateIDsByArea(topAreaGate.ID);
                        }
                        else
                        {
                            ids = m_ViewModel.MonitorAreaGateExts.Where(m => m.IsSelected && m.TypeID != 1).Select(mm => mm.ID).ToList();
                        }
                        ids = ids.OrderBy(i => i).ToList();
                        tableGrid.Width = 100 + ids.Count * 150 + 150;
                        Grid topGrid = GetTopGrid(ids);
                        topGrid.SetValue(Grid.RowProperty, 0);
                        Grid contentGrid = GetContentGrid(ids.Count);
                        contentGrid.SetValue(Grid.RowProperty, 1);
                        FillTimeColumnInContentGrid(contentGrid);
                        FillPassengerInContentGrid(contentGrid, ids, topAreaGate.ID);
                        tableGrid.Children.Add(topGrid);
                        tableGrid.Children.Add(contentGrid);

                    }
                }
                else
                {
                    selectAreaExt.each(s =>
                    {
                        // var source = m_ViewModel.GetWeekHistoryPassengerFlowByGate(isSingleArea, s.ID, dateTime);

                    });
                }

                //GridBorderHelper.ShowBorder(tableGrid);

                spContent.Children.Add(tableGrid);
            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                
            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                m_ViewModel.AreaExtends.each(a => a.IsSelected = false);

                var selectItem = cmbAreas.SelectedItem as AreaExtend;
                if (selectItem != null)
                {
                    selectItem.IsSelected = true;
                }

                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                m_ViewModel.SelectAreasChanged(selectedArea);

            }
        }


        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                                  startDatePicker.SelectedDate.Value.Month,
                                                  startDatePicker.SelectedDate.Value.Day,
                                                  0, 0, 0);
                DateTime nextDate = startTime.AddDays(1);
                DateTime endTime = new DateTime(nextDate.Year,
                                                nextDate.Month,
                                                nextDate.Day,
                                                0, 0, 0);

                if (endTime < startTime)
                {
                    MessageBox.Show("开始时间不能大于结束时间");
                }
                else
                {
                    m_ViewModel.RefreshAllShopPassengerFlows(startTime, endTime);
                }
            }
        }

        #endregion

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private DataGridTextColumn GetFirstDataGridColumn()
        {
            DataGridTextColumn titleColumn = new DataGridTextColumn();
            titleColumn.Header = "时段";
            titleColumn.Width = new DataGridLength(100);

            return titleColumn;
        }

        private Grid GetTableGrid()
        {
            Grid grid = new Grid();
            grid.Name = "tableGrid";
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            //grid.ShowGridLines = true;
            grid.Width = 1000;
            grid.Margin = new Thickness(30, 20, 30, 20);
            grid.RowDefinitions.Add(GetRowDefinition(80));
            RowDefinition row1 = new RowDefinition();
            row1.Height = new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
            grid.RowDefinitions.Add(row1);

            GridBorderHelper.ShowBorder(grid);
            return grid;
        }

        private Grid GetContentGrid(int count)
        {
            Grid grid = new Grid();
            grid.Name = "contentGrid";
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            grid.Margin = new Thickness(0, 0, 0, 0);

            int rowCount = 25;
            int columnCount = (count + 1) * 3 + 1;

            int index = 0;
            while (index < rowCount)
            {
                grid.RowDefinitions.Add(GetRowDefinition(40));
                index++;
            }

            index = 0;
            decimal percent = (decimal)1 / ((count + 1) * 3);
            percent = Math.Round(percent, 2);
            while (index < columnCount)
            {
                if (index == 0)
                {
                    ColumnDefinition column1 = new ColumnDefinition();
                    column1.Width = new System.Windows.GridLength(100, System.Windows.GridUnitType.Pixel);
                    grid.ColumnDefinitions.Add(column1);
                }
                else
                {
                    grid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));
                }
                index++;
            }
            GridBorderHelper.ShowBorder(grid);
            return grid;
        }

        private void FillTimeColumnInContentGrid(Grid contentGrid)
        {
            DateTime startTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0, 0);
            DateTime endTime = startTime.AddDays(1);
            DateTime tempTime = DateTime.Now;
            TextBlock tempText = null;
            string textStr = string.Empty;

            int index = 0;
            while (startTime < endTime)
            {
                tempTime = startTime.AddHours(-1);
                textStr = tempTime.ToString("HH:mm") + "--" + startTime.ToString("HH:mm");

                tempText = new TextBlock();
                tempText.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                tempText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                tempText.FontSize = 10;
                tempText.Text = textStr;
                tempText.SetValue(Grid.RowProperty, index);
                tempText.SetValue(Grid.ColumnProperty, 0);

                contentGrid.Children.Add(tempText);

                index++;
                startTime = startTime.AddHours(1);
            }

            tempText = new TextBlock();
            tempText.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            tempText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            tempText.FontSize = 10;
            tempText.Text = "总计";
            tempText.SetValue(Grid.RowProperty, index);
            tempText.SetValue(Grid.ColumnProperty, 0);

            contentGrid.Children.Add(tempText);
        }

        private void FillPassengerInContentGrid(Grid contentGrid, List<int> gateIDs,int areaID)
        {
            TextBlock tempText = null;
            string textStr = string.Empty;

            int columnIndex = 1;
            List<HistoryPassengerFlow> tempPassengerFlows = null;
            HistoryPassengerFlow tempPassengerFlow = null;
            gateIDs.each(id =>
            {
                DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                              startDatePicker.SelectedDate.Value.Month,
                              startDatePicker.SelectedDate.Value.Day,
                              0, 0, 0);
                DateTime endTime = startTime.AddDays(1);
                tempPassengerFlows = m_ViewModel.GetDayPassengerFlowByGateID(id, startTime, endTime, 60);
                AddSourceToDataGrid(contentGrid, tempPassengerFlows, columnIndex);
                columnIndex = columnIndex + 3;
            });

            //Set All
            DateTime startTime2 = new DateTime(startDatePicker.SelectedDate.Value.Year,
                              startDatePicker.SelectedDate.Value.Month,
                              startDatePicker.SelectedDate.Value.Day,
                              0, 0, 0);
            DateTime endTime2 = startTime2.AddDays(1);
            tempPassengerFlows = m_ViewModel.GetDayPassengerFlowByAreaID(areaID, startTime2, endTime2, 60);
            AddSourceToDataGrid(contentGrid, tempPassengerFlows, columnIndex);

            columnIndex = columnIndex + 3;

        }

        private void AddSourceToDataGrid(Grid contentGrid, List<HistoryPassengerFlow> tempPassengerFlows, int columnIndex)
        {
            int rowIndex = 0;
            DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                          startDatePicker.SelectedDate.Value.Month,
                                          startDatePicker.SelectedDate.Value.Day,
                                          0, 0, 0);
            DateTime endTime = startTime.AddDays(1);
            DateTime tempTime = DateTime.Now;
            HistoryPassengerFlow tempPassengerFlow = null;
            while (startTime < endTime)
            {
                tempPassengerFlow = tempPassengerFlows.Where(t => t.HistoryTime == startTime).FirstOrDefault();
                if (tempPassengerFlow != null)
                {
                    //In
                    AddContentToDataGrid(tempPassengerFlow.InCount.ToString(), contentGrid, rowIndex, columnIndex);

                    //Out
                    AddContentToDataGrid(tempPassengerFlow.OutCount.ToString(), contentGrid, rowIndex, columnIndex + 1);

                    //Differ
                    AddContentToDataGrid((tempPassengerFlow.InCount - tempPassengerFlow.OutCount).ToString(), contentGrid, rowIndex, columnIndex + 2);
                }
                rowIndex++;
                startTime = startTime.AddMinutes(60);
            }
            //All
            int inSum = tempPassengerFlows.Sum(s => s.InCount);
            int outSum = tempPassengerFlows.Sum(s => s.OutCount);
            AddContentToDataGrid(inSum.ToString(), contentGrid, rowIndex, columnIndex);
            AddContentToDataGrid(outSum.ToString(), contentGrid, rowIndex, columnIndex + 1);
            AddContentToDataGrid((inSum - outSum).ToString(), contentGrid, rowIndex, columnIndex + 2);
        }

        private void AddContentToDataGrid(string text, Grid contentGrid, int rowIndex, int columnIndex)
        {
            TextBlock tempText = new TextBlock();
            tempText.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            tempText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            tempText.Text = text;
            tempText.SetValue(Grid.RowProperty, rowIndex);
            tempText.SetValue(Grid.ColumnProperty, columnIndex);
            contentGrid.Children.Add(tempText);
        }

        private Grid GetTopGrid(List<int> gateOrAreas)
        {
            int count = gateOrAreas.Count;

            Grid grid = new Grid();
            grid.Name = "topGrid";
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            grid.Margin = new Thickness(0, 0, 0, 0);
            grid.Background = new SolidColorBrush(Color.FromArgb(255, 255, 245, 238));

            ColumnDefinition column1 = new ColumnDefinition();
            column1.Width = new System.Windows.GridLength(100, System.Windows.GridUnitType.Pixel);
            grid.ColumnDefinitions.Add(column1);

            int index = 0;
            index = 0;
            decimal percent = (decimal)1 / (count + 1);
            percent = Math.Round(percent, 2);
            while (index <= count)
            {
                grid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));
                index++;
            }

            //set first column [时段]
            TextBlock timeText = GetTextBlock(-1, 0, "时段");
            grid.Children.Add(timeText);

            //Set gate Golumns
            index = 1;
            gateOrAreas.each(g => {

                Grid columnGrid = new Grid();
                columnGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                columnGrid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                columnGrid.Margin = new Thickness(0, 0, 0, 0);
                //columnGrid.ShowGridLines = true;
                columnGrid.RowDefinitions.Add(GetRowDefinitionStart(0.5));
                columnGrid.RowDefinitions.Add(GetRowDefinitionStart(0.5));
                string gateName = m_ViewModel.GetGateName(g);
                TextBlock gateText = GetTextBlock(0, -1, gateName);
                columnGrid.Children.Add(gateText);
                Grid inOrOutGrid = GetInOrOutGrid(1, -1);
                GridBorderHelper.ShowBorder(inOrOutGrid);
                columnGrid.Children.Add(inOrOutGrid);

                columnGrid.SetValue(Grid.ColumnProperty, index);
                GridBorderHelper.ShowBorder(columnGrid);
                grid.Children.Add(columnGrid);
                index++;
            
            });

            //Set合计column
            Grid computeGrid = new Grid();
            computeGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            computeGrid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            computeGrid.Margin = new Thickness(0, 0, 0, 0);
            computeGrid.RowDefinitions.Add(GetRowDefinitionStart(0.5));
            computeGrid.RowDefinitions.Add(GetRowDefinitionStart(0.5));
            TextBlock computeText = GetTextBlock(0, -1, "合计");
            computeGrid.Children.Add(computeText);
            Grid inOrOutGrid2 = GetInOrOutGrid(1, -1);
            GridBorderHelper.ShowBorder(inOrOutGrid2);
            computeGrid.Children.Add(inOrOutGrid2);

            computeGrid.SetValue(Grid.ColumnProperty, index);

            GridBorderHelper.ShowBorder(computeGrid);
            grid.Children.Add(computeGrid);

            GridBorderHelper.ShowBorder(grid);
            return grid;
        }

        private Grid GetInOrOutGrid(int row, int column)
        {
            Grid inOutGrid = new Grid();
            inOutGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            inOutGrid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            inOutGrid.Margin = new Thickness(0, 0, 0, 0);
            //columnGrid.ShowGridLines = true;

            decimal percent = (decimal)1 / 3;
            percent = Math.Round(percent, 2);

            inOutGrid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));
            inOutGrid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));
            inOutGrid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));

            TextBlock inTextBolck = GetTextBlock(-1, 0, "进");
            TextBlock outTextBolck = GetTextBlock(-1, 1, "出");
            TextBlock differTextBolck = GetTextBlock(-1, 2, "差额");

            inOutGrid.Children.Add(inTextBolck);
            inOutGrid.Children.Add(outTextBolck);
            inOutGrid.Children.Add(differTextBolck);

            if (row >= 0)
            {
                inOutGrid.SetValue(Grid.RowProperty, row);
            }

            if (column >= 0)
            {
                inOutGrid.SetValue(Grid.ColumnProperty, column);
            }
            GridBorderHelper.ShowBorder(inOutGrid);
            return inOutGrid;

        }

        private RowDefinition GetRowDefinition(double height)
        {
            RowDefinition row1 = new RowDefinition();
            row1.Height = new System.Windows.GridLength(height, System.Windows.GridUnitType.Pixel);
            return row1;
        }

        private RowDefinition GetRowDefinitionStart(double height)
        {
            RowDefinition row1 = new RowDefinition();
            row1.Height = new System.Windows.GridLength(height, System.Windows.GridUnitType.Star);
            return row1;
        }

        private ColumnDefinition GetColumnDefinition(double width)
        {
            ColumnDefinition column1 = new ColumnDefinition();
            column1.Width = new System.Windows.GridLength(width, System.Windows.GridUnitType.Star);
            return column1;
        }

        private TextBlock GetTextBlock(int row, int column,string text)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.Text = text;
            textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            if (column >= 0)
            {
                textBlock.SetValue(Grid.ColumnProperty, column);
            }
            if(row>=0)
            {
                textBlock.SetValue(Grid.RowProperty, row);
            }

            return textBlock;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
